package com.weiyi.servlet03;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 * @description 使用inputStream方式上传文件
 * @author 惟一
 * @date 2020年6月26日下午5:55:58
 */
@WebServlet("/upload.do")
public class UploadDemo extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		byte[] body = readBody(req);
		String textBody = new String(body,"UTF-8");
		String filename = getFilename(textBody);
		Position p = getFilePosition(req,textBody);
		writeTo(filename,body,p);
	}

	class Position{
		int begin;
		int end;
		Position(int begin,int end){
			this.begin = begin;
			this.end = end;
		}
	}
	
	private void writeTo(String filename, byte[] body, Position p) throws IOException {
		FileOutputStream fileOutputStream = new FileOutputStream("F:\\"+filename);
		fileOutputStream.write(body, p.begin, (p.end-p.begin));
		fileOutputStream.flush();
		fileOutputStream.close();
	}
	
	private Position getFilePosition(HttpServletRequest req, String textBody) throws UnsupportedEncodingException {
		//取得文件边界信息
		String contentType = req.getContentType();
		String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
		//取得实际上传文件的起始与结束位置
		int pos = textBody.indexOf("filename=\"");
		pos = textBody.indexOf("\n",pos)+1;
		pos = textBody.indexOf("\n",pos)+1;
		pos = textBody.indexOf("\n",pos)+1;
		int boundaryLoc = textBody.indexOf(boundaryText,pos)-4;
		int begin = ((textBody.substring(0,pos)).getBytes("ISO-8859-1").length);
		int end = ((textBody.substring(0,boundaryLoc)).getBytes("ISO-8859-1").length);
		return new Position(begin,end);
	}

	private String getFilename(String textBody) {
		String filename = textBody.substring(textBody.indexOf("filename=\"")+10);
		filename = filename.substring(0,filename.indexOf("\n"));
		filename = filename.substring(filename.lastIndexOf("\\")+1,filename.indexOf("\""));		
		return filename;
	}

	private byte[] readBody(HttpServletRequest req) throws IOException {
		int contentLength = req.getContentLength();
		byte body[] = new byte[contentLength];
		DataInputStream dataInputStream = new DataInputStream(req.getInputStream());
		int totalBytes = 0;
		while(totalBytes < contentLength) {
			int bytes = dataInputStream.read(body,totalBytes,contentLength);
			totalBytes += bytes;
		}
		return body;
		
	}
}
